var http = require("http");
var dns = require('dns');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');

http.createServer(function (req, resp) {
    req.setEncoding('utf8');
    resp.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8'
    });

    var reqUrl = url.parse(req.url).pathname;
    console.log(reqUrl);
    if (reqUrl == '/parse') {
        parseDns(req, resp);
    } else {
        var filePath = __dirname + "/" + url.parse("parse.html").pathname;
        var parsePage = fs.readFileSync(filePath);
        resp.end(parsePage);
    }
}).listen(3000);

function parseDns(req, res) {
    // 对于req中post方法传递过来的数据，需要使用req.addListener()来获取数据；
    var data = "";
    req.addListener('data', function (dataChunk) {
        data += dataChunk;
        console.log(dataChunk);
    });
    req.addListener('end', function () {
        getDns(data, function (domin, address) {
            res.end(address.join(','));
        });
    });
}

function getDns(data, callback) {
    var domin = querystring.parse(data).input;
    if (domin.indexOf("http://") >= 0) {
        domin = domin.replace("http://", "");
    } else if (domin.indexOf("https://") >= 0) {
        domin = domin.replace("https://", "");
    }

    dns.resolve(domin + '', function (err, address) {
        if (!address) {
            address = ['domin is not exists'];
        }
        callback(domin, address);
    });
}
